#ifndef DATAFLOW_DETAIL_WORKER_H
#define DATAFLOW_DETAIL_WORKER_H

#include <assert.h>

#include <QThread>

#include "Scheduler.h"

/*
#include <stdlib.h>
#include <iostream>
inline int slowFunction(void)
{
	double d = 0.0;
	for (int i=0; i<10000; ++i)
	{
		d += double(rand());
	}
	return int(d);
}
*/

namespace DataFlow
{

namespace Detail
{

class Worker : public QThread
{
	Q_OBJECT

	public:

		typedef QThread BaseType;
		typedef Worker  ThisType;

		Worker(Scheduler * tScheduler, QObject * parent = 0)
			: BaseType(parent)
			, scheduler(tScheduler)
			, active(true)
		{
			assert(tScheduler != 0);
		}

		virtual ~Worker(void)
		{
			this->active = false;
			this->wait();
			this->scheduler = 0;
		}

	signals:

		void taskStarted  (int task, DataFlow::ArgumentArray input);
		void taskFinished (int task, DataFlow::ArgumentArray input, DataFlow::ArgumentArray output);

	protected:

		Scheduler * scheduler;
		bool        active;

		virtual void run(void)
		{
			//static int x = 0;
			while (this->active)
			{
				TaskInstance * t = this->scheduler->nextTaskInstance();
				if (t == 0) continue;

				emit taskStarted(t->taskId, t->input);
				t->run();
				//x += slowFunction();
				//std::cout << "T[" << ((unsigned int)(QThread::currentThreadId())) << "]: " << x << std::endl;
				emit taskFinished(t->taskId, t->input, t->output);

				this->scheduler->taskInstanceFinished(t);
			}
		}
};

}

}

#endif // DATAFLOW_DETAIL_WORKER_H
